package fr.toto.settings.settingPanels;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.InputMethodListener;
import java.awt.event.InputMethodEvent;

public class PanelWebUI extends JPanel {

	private static final long serialVersionUID = -6355808966495864171L;
	private JCheckBox webUI;
	private JTextField webUIPort;

	public PanelWebUI(boolean actif, String portWeb) {

		this.setMaximumSize(new Dimension(32767, 40));
		this.setSize(new Dimension(280, 35));
		this.setAlignmentY(Component.TOP_ALIGNMENT);

		webUI = new JCheckBox(" Interface web");

		final JLabel lblNewLabel = new JLabel("      Port :");

		webUIPort = new JTextField();
		webUIPort.setText("");
		webUIPort.addInputMethodListener(new InputMethodListener() {
			public void caretPositionChanged(InputMethodEvent arg0) {
			}
			public void inputMethodTextChanged(InputMethodEvent arg0) {
				webUIPort.setText(webUIPort.getText().replaceAll("[^0-9]", ""));
			}
		});
		webUIPort.setColumns(5);

		if (portWeb != null && !portWeb.isEmpty())
			webUIPort.setText(portWeb);
		else
			actif = false;

		if (actif) {
			webUI.setSelected(true);
		} else {
			webUI.setSelected(false);
			lblNewLabel.setEnabled(false);
			webUIPort.setEnabled(false);
		}

		webUI.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (webUI.isSelected()) {
					lblNewLabel.setEnabled(true);
					webUIPort.setEnabled(true);
				} else {
					lblNewLabel.setEnabled(false);
					webUIPort.setEnabled(false);
				}
			}
		});

		this.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		this.add(webUI);
		this.add(lblNewLabel);
		this.add(webUIPort);

	}

	public boolean isOn() {
		return webUI.isSelected();
	}

	public String webPort() {
		return webUIPort.getText();
	}

	public int getPort() {
		String t = webUIPort.getText().replaceAll("[^0-9]", "");
		if (t.isEmpty()) return 0;
		return Integer.parseInt(t);
	}

}
